﻿using HSF.ModuleManager.Markdown;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEditor.IMGUI.Controls;
using UnityEngine;

namespace HSFModule
{
    static class ToolbarStyles
    {
        public static readonly GUIStyle CommandButtonStyle;
        public static readonly GUIStyle ToolBarExtenderBtnStyle;
        static ToolbarStyles()
        {
            CommandButtonStyle = new GUIStyle("Command")
            {
                fontSize = 12,
                alignment = TextAnchor.MiddleCenter,
                imagePosition = ImagePosition.ImageAbove,
                fontStyle = FontStyle.Bold,
                fixedWidth = 100,
                fixedHeight = 18
            };
            ToolBarExtenderBtnStyle = new GUIStyle("Command")
            {
                fontSize = 12,
                alignment = TextAnchor.MiddleCenter,
                imagePosition = ImagePosition.ImageAbove,
                fontStyle = FontStyle.Normal,
                fixedHeight = 18
            };
        }
    }

    /// <summary>
    /// 模块类型
    /// </summary>
    public enum ModuleType
    {
        /// <summary>
        /// 扩展包
        /// </summary>
        ExtendPackage,
        /// <summary>
        /// 说明文档
        /// </summary>
        Documentation
    }
    public enum ShowStartUp
    {
        Always,
        Never
    }

    // 新增图片数据类
    public class MdImageData
    {
        public string altText;
        public string imagePath;
        public Vector2 position;
    }
    public class MarkdownViewerWindow : EditorWindow
    {
        private MarkdownViewer _markdownViewer;
        private MdNode _rootNode;
        private TreeViewState _treeViewState;
        private MdTreeView _treeView;
        private Vector2 _contentScroll;
        private string _currentContent = "";
        private float _splitWidth = 300;
        private GUIStyle _wrapStyle;
        // 类成员变量添加样式缓存（避免重复创建）
        private GUIStyle fileNameStyle;
        private GUIStyle timeStyle;
        // 在类顶部添加固定路径配置
        private const string FIXED_MD_PATH = "Packages/com.sevene.hsfmodule/HSFModule.md"; // 可修改为实际路径
        private const string SHOW_AT_STARTUP_KEY = "HSFModule_ShowAtStartup";
        private ModuleType _showModuleType = ModuleType.Documentation;
        private ShowStartUp _showStartUp = ShowStartUp.Always;
        // 新增成员变量
        private List<MdImageData> _images = new List<MdImageData>();
        private Dictionary<string, Texture2D> _imageCache = new Dictionary<string, Texture2D>();
        private const float ImageSpacing = 10f;
        private GUIContent _helpGC;
        [MenuItem("Tools/MSF/MSFModule文档&包管理器")]
        public static void Init() => GetWindow<MarkdownViewerWindow>("MSFModule文档&包管理器");

        void OnEnable()
        {

            _treeViewState = new TreeViewState();
            LoadFixedMarkdown();
            _helpGC = new GUIContent();
            _helpGC.image = EditorGUIUtility.IconContent("TreeEditor.Refresh").image;
            _helpGC.tooltip = "Reload";
            // 加载启动配置
            if (EditorPrefs.HasKey(SHOW_AT_STARTUP_KEY))
                _showStartUp = (ShowStartUp)EditorPrefs.GetInt(SHOW_AT_STARTUP_KEY);
            else
                _showStartUp = ShowStartUp.Always; // 默认值
        }
        void DrawToolbar()
        {

            EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
            GUILayout.Label($"当前版本：V1.0.1", EditorStyles.label);
            if (GUILayout.Button("类型：" + _showModuleType.ToString(), EditorStyles.toolbarDropDown))
            {
                GenericMenu gm = new GenericMenu();
                gm.AddItem(new GUIContent("ExtendPackage"), _showModuleType == ModuleType.ExtendPackage, () =>
                {
                    _showModuleType = ModuleType.ExtendPackage;

                });
                gm.AddItem(new GUIContent("Documentation"), _showModuleType == ModuleType.Documentation, () =>
                {
                    _showModuleType = ModuleType.Documentation;

                });
                gm.ShowAsContext();
            }
            GUILayout.Label($"开发者：爱吃栗子的虎", EditorStyles.label);
            EditorGUILayout.LabelField($"最后更新：{File.GetLastWriteTime(FIXED_MD_PATH):yyyy-MM-dd HH:mm}", GUILayout.Width(180));
            if (GUILayout.Button(new GUIContent("Tortoise Git", "Tortoise Git"), ToolbarStyles.CommandButtonStyle))
            {
                //TortoiseGitWindow.OpenWindow(this);
            }
            if (GUILayout.Button(new GUIContent("Git Bash", "Git Bash"), ToolbarStyles.CommandButtonStyle))
            {
                //GitBashWindow.OpenWindow(this);
            }
            if (GUILayout.Button(new GUIContent("Credentials", "Credentials"), ToolbarStyles.CommandButtonStyle))
            {
                //CredentialsProviderWindow.OpenWindow(this, _modulesLibrary.SetCredentials);
            }
            if (GUILayout.Button(_helpGC, ToolbarStyles.ToolBarExtenderBtnStyle))
            {
                ClearImageCache();
                LoadFixedMarkdown();
                _treeView = new MdTreeView(_treeViewState, _rootNode, this);
                Repaint();
            }
            EditorGUILayout.EndHorizontal();

        }
        // 在MarkdownViewerWindow类中添加缓存清理方法
        private void ClearImageCache()
        {
            foreach (var tex in _imageCache.Values)
            {
                UnityEngine.Object.DestroyImmediate(tex, true);
            }
            _imageCache.Clear();
            _images.Clear();
        }
        private void LoadFixedMarkdown()
        {
            string fullPath = Path.GetFullPath(FIXED_MD_PATH);
            if (!File.Exists(fullPath))
            {
                Debug.LogError($"固定文档加载失败：{fullPath}");
                _currentContent = $"文档缺失：{FIXED_MD_PATH}";
                return;
            }

            LoadMarkdownFile(fullPath);
            titleContent = new GUIContent(Path.GetFileNameWithoutExtension(FIXED_MD_PATH));
        }
        void OnGUI()
        {
            // 初始化样式（首次调用时创建）
            if (fileNameStyle == null)
            {
                fileNameStyle = new GUIStyle(EditorStyles.miniLabel)
                {
                    fontSize = 14,
                    padding = new RectOffset(5, 5, 3, 3), // 上下左右边距
                    fixedHeight = 28 // 固定高度
                };

                timeStyle = new GUIStyle(EditorStyles.miniLabel)
                {
                    fontSize = 12,
                    alignment = TextAnchor.MiddleRight,
                    padding = new RectOffset(5, 10, 3, 3),
                    fixedHeight = 28
                };
            }
            DrawToolbar();
            DrawMainView();
            EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
            GUIStyle gUIStyle = new GUIStyle();
            gUIStyle.normal.textColor = Color.green;
            GUILayout.Label($"以上工具部分功能采用现成框架，部分模块会在后期开发过程当中进行逐步更新完善", gUIStyle);
            if (GUILayout.Button("Show At StartUp：" + _showStartUp.ToString(), EditorStyles.toolbarDropDown))
            {
                GenericMenu gm = new GenericMenu();
                gm.AddItem(new GUIContent("Always"), _showStartUp == ShowStartUp.Always, () =>
                {
                    _showStartUp = ShowStartUp.Always;
                    EditorPrefs.SetInt(SHOW_AT_STARTUP_KEY, (int)_showStartUp);
                });
                gm.AddItem(new GUIContent("Never"), _showStartUp == ShowStartUp.Never, () =>
                {
                    _showStartUp = ShowStartUp.Never;
                    EditorPrefs.SetInt(SHOW_AT_STARTUP_KEY, (int)_showStartUp);
                });
                gm.ShowAsContext();
            }
            EditorGUILayout.EndHorizontal();
        }


        void DrawMainView()
        {
            if (_showModuleType == ModuleType.Documentation)
            {
                EditorGUILayout.BeginHorizontal();
                DrawTreeView();
                DrawContentPanel();
                EditorGUILayout.EndHorizontal();
            }
            else
            {
                DrawAllModuleView(); // 新增AllModule视图
            }
        }
        // 新增AllModule视图绘制方法
        void DrawAllModuleView()
        {
            // 示例数据 - 实际应从模块管理系统获取
            var demoModules = new List<string>
    {
        "Core System Module",
        "Network Module",
        "AI Framework",
        "UI System"
    };
            EditorGUILayout.BeginVertical(GUILayout.ExpandWidth(true));

            // 模块列表标题
            EditorGUILayout.LabelField("Available Modules", EditorStyles.largeLabel, GUILayout.Height(30));

            // 模块列表
            _contentScroll = EditorGUILayout.BeginScrollView(_contentScroll);
            foreach (var module in demoModules)
            {
                EditorGUILayout.BeginHorizontal("Box");
                GUILayout.Label(module, GUILayout.Width(200));

                // 状态显示
                EditorGUILayout.LabelField("v1.2.3", GUILayout.Width(80));
                EditorGUILayout.LabelField("Installed", GUILayout.Width(80));

                // 操作按钮
                if (GUILayout.Button("Update", GUILayout.Width(80)))
                {
                    Debug.Log($"Updating module: {module}");
                }

                EditorGUILayout.EndHorizontal();
            }
            EditorGUILayout.EndScrollView();

            EditorGUILayout.EndVertical();
            GUILayout.BeginHorizontal();
            if (GUILayout.Button("Create", "ButtonLeft"))
            {
                //_isCreateModule = true;
                //_isEditModule = false;
                //_currentEditModule = null;
            }
            if (GUILayout.Button("Open", "ButtonMid"))
            {
                string path = EditorUtility.OpenFolderPanel("Open Module", Application.dataPath, "");
                //if (!string.IsNullOrEmpty(path))
                //{
                //    _modulesLibrary.OpenModule(path);
                //}
            }
            //GUI.enabled = CurrentModule != null && !CurrentModule.IsLocalExist;
            if (GUILayout.Button("Edit", "ButtonMid"))
            {
                //_isCreateModule = false;
                //_isEditModule = true;
                //_currentEditModule = CurrentModule;
                //_inputModuleLocalPath = _currentEditModule.Path;
                //_inputModuleRemotePath = _currentEditModule.RemotePath;
            }
            //GUI.enabled = CurrentModule != null;
            if (GUILayout.Button("Remove", "ButtonMid"))
            {
                //_modulesLibrary.RemoveModule(CurrentModule);
                //CurrentModule = null;
                //_currentEditModule = null;
            }
            GUI.enabled = true;
            GUI.backgroundColor = Color.yellow;
            if (GUILayout.Button("Pull All", "ButtonRight"))
            {
                if (EditorUtility.DisplayDialog("Pull All", "Are you sure you want to Pull all modules?", "Yes", "No"))
                {
                    // _modulesLibrary.PullAll(() => { AssetDatabase.Refresh(); });
                }
            }
            GUI.backgroundColor = Color.white;
            GUILayout.EndHorizontal();
        }
        void DrawTreeView()
        {
            EditorGUILayout.BeginVertical(GUILayout.Width(_splitWidth));
            if (_treeView != null)
                _treeView.OnGUI(GUILayoutUtility.GetRect(0, 0, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)));

            EditorGUILayout.EndVertical();

        }



        void DrawContentPanel()
        {
            // 将 _currentContent 按代码块与普通文本进行分段
            var segments = ParseMarkdownSegments(_currentContent);

            EditorGUILayout.BeginVertical(GUILayout.ExpandWidth(true));
            _contentScroll = EditorGUILayout.BeginScrollView(_contentScroll, GUIStyle.none, GUI.skin.verticalScrollbar);

            // 普通文本样式
            GUIStyle normalStyle = new GUIStyle(EditorStyles.label)
            {
                richText = true,
                wordWrap = true,
                fontSize = 12
            };

            // 代码块样式：使用等宽字体、浅色背景和内边距
            GUIStyle codeBlockStyle = new GUIStyle(EditorStyles.textArea)
            {
                richText = true,
                wordWrap = true,
                fontSize = 12,
                // 尝试使用 Consolas 字体，若不存在则使用默认字体
                font = Font.CreateDynamicFontFromOSFont("Consolas", 12) ?? EditorStyles.textArea.font,
                padding = new RectOffset(4, 4, 4, 4)
            };
            // 设置背景纹理（浅灰色背景）
            codeBlockStyle.normal.background = MakeTex(2, 2, new Color(0f, 0f, 0f));
            // 遍历每个分段并进行绘制
            foreach (var segment in segments)
            {
                if (string.IsNullOrWhiteSpace(segment.text))
                    continue;
                if (segment.isCodeBlock)
                {
                    // 代码块部分保持原格式
                    string codeText = segment.text;
                    // 使用 GUILayoutUtility.GetRect 获取适合代码块显示的区域
                    Rect codeRect = GUILayoutUtility.GetRect(new GUIContent(segment.text), codeBlockStyle, GUILayout.ExpandWidth(true));
                    // 绘制代码块背景
                    GUI.Box(codeRect, GUIContent.none, codeBlockStyle);
                    // 绘制代码块文本
                    GUI.Label(codeRect, segment.text, codeBlockStyle);

                    // 在代码块右上角绘制复制按钮
                    float buttonWidth = 50f;
                    float buttonHeight = 18f;
                    float margin = 2f;
                    Rect buttonRect = new Rect(codeRect.xMax - buttonWidth - margin, codeRect.y + margin, buttonWidth, buttonHeight);
                    if (GUI.Button(buttonRect, "复制", EditorStyles.miniButton))
                    {
                        EditorGUIUtility.systemCopyBuffer = segment.text;
                    }
                }
                else
                {
                    // 对非代码块部分先清理多余空行
                    string cleanText = Regex.Replace(segment.text.Trim(), @"(\r?\n\s*){2,}", "\n");
                    DrawMarkdownNonCodeSegment(segment.text, normalStyle);
                }
                GUILayout.Space(2); // 分段之间增加间距
            }

            EditorGUILayout.EndScrollView();
            EditorGUILayout.EndVertical();
        }
        /// <summary>
        /// 绘制非代码块部分的 Markdown 内容，支持解析链接和图片
        /// </summary>
        void DrawMarkdownNonCodeSegment(string text, GUIStyle style)
        {
            string[] lines = text.Split(new[] { '\n' }, System.StringSplitOptions.None);
            // 定义列表符号样式，固定宽度并垂直顶对齐
            GUIStyle bulletStyle = new GUIStyle(EditorStyles.label)
            {
                alignment = TextAnchor.UpperLeft,
                fixedWidth = 10,
                richText = true
            };
            foreach (string line in lines)
            {
                string trimmed = line.Trim();
                if (string.IsNullOrEmpty(trimmed))
                    continue;

                // 检测有序列表项（如 "1. 文本"）
                Match orderedMatch = Regex.Match(trimmed, @"^(\d+)\.\s+(.*)");
                if (orderedMatch.Success)
                {
                    string marker = orderedMatch.Groups[1].Value + ".";
                    string content = orderedMatch.Groups[2].Value;
                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Label(marker, bulletStyle);
                    DrawInlineMarkdown(content, style);
                    EditorGUILayout.EndHorizontal();
                }
                else
                {
                    // 检测无序列表项（如 "- 文本" 或 "* 文本" 或 "+ 文本"）
                    Match unorderedMatch = Regex.Match(trimmed, @"^[-+*]\s+(.*)");
                    if (unorderedMatch.Success)
                    {
                        string content = unorderedMatch.Groups[1].Value;
                        EditorGUILayout.BeginHorizontal();
                        GUILayout.Label("•", bulletStyle);
                        DrawInlineMarkdown(content, style);
                        EditorGUILayout.EndHorizontal();
                    }
                    else
                    {
                        // 非列表行按内联 Markdown 解析
                        DrawInlineMarkdown(trimmed, style);
                    }
                }
                GUILayout.Space(2);
            }
        }
        /// <summary>
        /// 解析单行内联 Markdown（链接和图片）的显示
        /// </summary>
        void DrawInlineMarkdown(string text, GUIStyle style)
        {
            int lastIndex = 0;
            // 匹配 Markdown 链接或图片的语法，如 [text](url) 或 ![alt](path)
            string pattern = @"(!?\[[^\]]+\]\([^)]*\))";
            var matches = Regex.Matches(text, pattern);
            // 修改后的正则表达式（增加对复杂 URL 的支持）
            // 优先处理 GitHub 徽章
            var badgeMatch = Regex.Match(text,
                @"\[!\[([^\]]*)\]\(([^\)]+)\)\]\(([^\)]+)\)",
                RegexOptions.IgnoreCase);
            if (badgeMatch.Success)
            {
                var altText = badgeMatch.Groups[1].Value;
                var imageUrl = badgeMatch.Groups[2].Value.Trim();
                var targetUrl = badgeMatch.Groups[3].Value.Trim();

                DrawGitHubBadge(altText, imageUrl, targetUrl);
                return;
            }
            foreach (Match match in matches)
            {
                if (match.Index > lastIndex)
                {
                    string plainText = text.Substring(lastIndex, match.Index - lastIndex);
                    // 转换内联 HTML 标签为 Unity RichText 格式
                    EditorGUILayout.LabelField(ConvertHtmlToRichText(plainText), style);
                }
                string markdown = match.Value;
                if (markdown.StartsWith("!"))
                {
                    // 图片：格式 ![alt](图片路径)
                    var imageMatch = Regex.Match(markdown, @"!\[([^\]]*)\]\(([^)]*)\)");
                    if (imageMatch.Success)
                    {
                        string altText = imageMatch.Groups[1].Value;
                        string imagePath = imageMatch.Groups[2].Value;
                        Texture2D tex = AssetDatabase.LoadAssetAtPath<Texture2D>(imagePath);
                        if (tex != null)
                        {
                            GUILayout.Label(tex, GUILayout.MaxWidth(400));
                        }
                        else
                        {
                            EditorGUILayout.LabelField($"[图片未找到：{altText}]", style);
                        }
                    }
                }
                else
                {
                    // 链接：格式 [text](url)
                    var linkMatch = Regex.Match(markdown, @"\[(.*?)\]\((.*?)\)");
                    if (linkMatch.Success)
                    {
                        string linkText = linkMatch.Groups[1].Value;
                        string url = linkMatch.Groups[2].Value;
                        if (GUILayout.Button(linkText, EditorStyles.linkLabel))
                        {
                            Application.OpenURL(url);
                        }
                    }
                }
                lastIndex = match.Index + match.Length;
            }
            if (lastIndex < text.Length)
            {
                string remainingText = text.Substring(lastIndex);
                EditorGUILayout.LabelField(ConvertHtmlToRichText(remainingText), style);
            }
        }



        string FormatContent(string content)
        {
            // 第一遍处理：保持类名完整
            content = Regex.Replace(content, @"(\b[A-Z]\w+\b)",
                "<color=#87CEEB>\\$1</color>"); // 天蓝色高亮

            // 第二遍处理：强制在类名前后保留不可分割空格
            return Regex.Replace(content, @"(<color=#87CEEB>.*?</color>)",
                "\u00A0\\$1\u00A0"); // Unicode非换行空格
        }


        void LoadMarkdownFile(string path)
        {
            if (!File.Exists(path)) return;

            string mdContent = File.ReadAllText(path);
            ParseMarkdown(mdContent);
            titleContent = new GUIContent(_rootNode?.title ?? "MD Viewer");
            _treeView = new MdTreeView(_treeViewState, _rootNode, this);
            // 新增自动选择逻辑
            if (_rootNode.children.Count > 0)
            {
                var firstNode = GetFirstContentNode(_rootNode);
                _treeView.SetSelection(new List<int> { firstNode.GetHashCode() });
                SelectNode(firstNode);
            }
        }
        MdNode GetFirstContentNode(MdNode root)
        {
            // 深度优先搜索第一个有内容的节点
            var stack = new Stack<MdNode>(root.children);
            while (stack.Count > 0)
            {
                var node = stack.Pop();
                if (!string.IsNullOrWhiteSpace(node.content))
                    return node;

                foreach (var child in node.children.AsEnumerable().Reverse())
                    stack.Push(child);
            }
            return root;
        }
        void ParseMarkdown(string mdContent)
        {
            _rootNode = new MdNode { depth = 0 };
            Stack<MdNode> nodeStack = new Stack<MdNode>();
            nodeStack.Push(_rootNode);

            StringReader reader = new StringReader(mdContent);
            string line;
            MdNode currentNode = _rootNode;

            while ((line = reader.ReadLine()) != null)
            {
                var match = Regex.Match(line, @"^(#+)\s*(.*)");
                if (match.Success)
                {
                    int depth = match.Groups[1].Value.Length;
                    string title = match.Groups[2].Value.Trim();

                    MdNode newNode = new MdNode
                    {
                        depth = depth,
                        title = title,
                        parent = nodeStack.Peek()
                    };

                    // 寻找正确的父节点
                    while (nodeStack.Peek().depth >= depth)
                        nodeStack.Pop();

                    nodeStack.Peek().children.Add(newNode);
                    nodeStack.Push(newNode);
                    currentNode = newNode;
                }
                else if (currentNode != null)
                {
                    currentNode.content += line + "\n";
                }
            }
        }
        /// <summary>
        /// 将 Markdown 内容按代码块与普通文本分段解析
        /// </summary>
        /// <param name="markdown">Markdown 文本</param>
        /// <returns>分段列表</returns>
        private List<MarkdownSegment> ParseMarkdownSegments(string markdown)
        {
            List<MarkdownSegment> segments = new List<MarkdownSegment>();
            StringReader reader = new StringReader(markdown);
            bool inCodeBlock = false;
            System.Text.StringBuilder segmentBuilder = new System.Text.StringBuilder();
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                if (line.Trim().StartsWith("```"))
                {
                    // 若当前处于代码块内，则结束代码块
                    if (inCodeBlock)
                    {
                        segments.Add(new MarkdownSegment { isCodeBlock = true, text = segmentBuilder.ToString() });
                        segmentBuilder.Clear();
                        inCodeBlock = false;
                    }
                    else
                    {
                        // 如果之前有普通文本，先保存
                        if (segmentBuilder.Length > 0)
                        {
                            segments.Add(new MarkdownSegment { isCodeBlock = false, text = segmentBuilder.ToString() });
                            segmentBuilder.Clear();
                        }
                        inCodeBlock = true;
                    }
                }
                else
                {
                    segmentBuilder.AppendLine(line);
                }
            }
            // 添加剩余内容
            if (segmentBuilder.Length > 0)
            {
                segments.Add(new MarkdownSegment { isCodeBlock = inCodeBlock, text = segmentBuilder.ToString() });
            }
            return segments;
        }

        /// <summary>
        /// 辅助方法：创建指定颜色的纹理
        /// </summary>
        private Texture2D MakeTex(int width, int height, Color col)
        {
            Color[] pix = new Color[width * height];
            for (int i = 0; i < pix.Length; i++)
            {
                pix[i] = col;
            }
            Texture2D result = new Texture2D(width, height);
            result.SetPixels(pix);
            result.Apply();
            return result;
        }
        /// <summary>
        /// 将内联 HTML 标签转换为 Unity RichText 格式
        /// 例如：将 <strong> 转换为 <b>，
        /// 将 <font size="20"> 转换为 <b><size=20>（同时使内容加粗），
        /// 并将 </font> 转换为 </size></b>
        /// </summary>
        /// <param name="input">待转换的字符串</param>
        /// <returns>转换后的字符串</returns>
        public static string ConvertHtmlToRichText(string input)
        {
            if (string.IsNullOrEmpty(input))
                return input;

            // 转换 <strong> 标签为 <b>
            input = Regex.Replace(input, @"<\s*strong\s*>", "<b>", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, @"<\s*/\s*strong\s*>", "</b>", RegexOptions.IgnoreCase);

            // 将 <font size="20"> 标签转换为 <b><size=20> ，同时在关闭时转换为 </size></b>
            input = Regex.Replace(input, @"<\s*font\s+size\s*=\s*""?(\d+)""?\s*>", "<b><size=$1>", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, @"<\s*/\s*font\s*>", "</size></b>", RegexOptions.IgnoreCase);

            return input;
        }
        // 在 MarkdownViewerWindow 类中添加以下方法
        private void DrawGitHubBadge(string altText, string imageUrl, string targetUrl)
        {
            // 添加 URL 验证
            if (!IsValidUrl(imageUrl) || !IsValidUrl(targetUrl))
            {
                Debug.LogWarning($"Invalid URL detected: Image={imageUrl} | Target={targetUrl}");
                return;
            }
            // 异步加载图片纹理
            if (!_imageCache.ContainsKey(imageUrl))
            {
                _imageCache[imageUrl] = new Texture2D(2, 2);
                LoadImageTexture(imageUrl);
            }
            Texture2D badgeTexture = _imageCache[imageUrl];
            // 添加错误处理
            if (badgeTexture == null)
            {
                GUILayout.Label($"⚠️ Failed to load: {altText}", GUI.skin.box);
                return;
            }
            // 创建可点击的图片按钮
            GUIStyle badgeStyle = new GUIStyle(GUI.skin.label)
            {
                fixedHeight = 20,
                fixedWidth = badgeTexture != null ? badgeTexture.width : 120,
                margin = new RectOffset(0, 5, 2, 2)
            };
            if (GUILayout.Button(new GUIContent(badgeTexture), badgeStyle))
            {
                Application.OpenURL(targetUrl);
            }
        }
        private async void LoadImageTexture(string url)
        {
            // 对 URL 进行编码处理
            string encodedUrl = UnityEngine.Networking.UnityWebRequest.EscapeURL(url);
            using (var www = UnityEngine.Networking.UnityWebRequestTexture.GetTexture(encodedUrl))
            {
                var asyncOp = www.SendWebRequest();
                while (!asyncOp.isDone) await System.Threading.Tasks.Task.Yield();
                if (www.result == UnityEngine.Networking.UnityWebRequest.Result.Success)
                {
                    _imageCache[url] = ((UnityEngine.Networking.DownloadHandlerTexture)www.downloadHandler).texture;
                    Repaint(); // 触发界面刷新
                }
            }
        }
        private bool IsValidUrl(string url)
        {
            return Uri.TryCreate(url, UriKind.Absolute, out var uriResult)
                   && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
        }

        private void SelectNode(MdNode node)
        {
            if (_showModuleType == ModuleType.Documentation)
            {
                _currentContent = node.content.Trim();
            }
            else
            {
                // 处理模块选择逻辑
                Debug.Log($"Selected module: {node.title}");
            }
        }

        class MdNode
        {
            public int depth;
            public string title;
            public string content;
            public MdNode parent;
            public List<MdNode> children = new List<MdNode>();
        }

        class MdTreeView : TreeView
        {
            private MdNode _root;
            private MarkdownViewerWindow _window;
            // 新增高度常量
            private const float ButtonHeight = 28f;  // 可自定义的高度值
            public MdTreeView(TreeViewState state, MdNode root, MarkdownViewerWindow window) : base(state)
            {
                _root = root;
                _window = window;
                showAlternatingRowBackgrounds = true;
                Reload();
                ExpandAll(); // 初始化时展开所有节点
            }
            // 递归展开方法
            public void ExpandAll()
            {
                if (rootItem?.children == null) return;
                foreach (var child in rootItem.children)
                {
                    SetExpandedRecursive(child.id, true);
                }
            }
            private void SetExpandedRecursive(int id, bool expand)
            {
                var item = FindItem(id, rootItem);
                if (item == null) return;
                SetExpanded(id, expand);
                if (item.hasChildren)
                {
                    foreach (var child in item.children)
                    {
                        SetExpandedRecursive(child.id, expand);
                    }
                }
            }
            protected override TreeViewItem BuildRoot()
            {
                var rootItem = new TreeViewItem(-1, -1);
                BuildTreeItems(rootItem, _root.children);
                return rootItem;
            }

            void BuildTreeItems(TreeViewItem parent, List<MdNode> nodes)
            {
                foreach (var node in nodes)
                {
                    var item = new TreeViewItem(node.GetHashCode(), node.depth - 1, node.title)
                    {
                        icon = GetDepthIcon(node.depth)
                    };
                    parent.AddChild(item);
                    if (node.children.Count > 0) BuildTreeItems(item, node.children);
                }
            }

            protected override void SelectionChanged(IList<int> selectedIds)
            {
                base.SelectionChanged(selectedIds);
                if (selectedIds.Count > 0)
                {
                    var node = FindNode(_root.children, selectedIds[0]);
                    _window.SelectNode(node);
                }
                else
                {
                    _window.SelectNode(null); // 清除显示
                }
            }
            // 扩展节点查找方法
            public MdNode FindNode(int id)
            {
                return FindNode(_root.children, id);
            }
            MdNode FindNode(List<MdNode> nodes, int id)
            {
                foreach (var node in nodes)
                {
                    if (node.GetHashCode() == id) return node;
                    var child = FindNode(node.children, id);
                    if (child != null) return child;
                }
                return null;
            }

            Texture2D GetDepthIcon(int depth)
            {
                return depth switch
                {
                    1 => EditorGUIUtility.IconContent("d_UnityLogo").image as Texture2D,
                    2 => EditorGUIUtility.IconContent("d_FolderOpened Icon").image as Texture2D,
                    _ => EditorGUIUtility.IconContent("d_TextAsset Icon").image as Texture2D
                };
            }
        }
        // 辅助类：表示一段 Markdown 内容
        private class MarkdownSegment
        {
            public bool isCodeBlock;
            public string text;
        }

    }
    [InitializeOnLoad]
    public static class MarkdownViewerAutoLauncher
    {
        static MarkdownViewerAutoLauncher()
        {
            // 延迟调用以避免初始化早期的问题
            EditorApplication.update += DelayedOpen;
        }

        private static void DelayedOpen()
        {
            EditorApplication.update -= DelayedOpen;

            if (EditorPrefs.GetInt("HSFModule_ShowAtStartup", 0) == (int)ShowStartUp.Always)
            {
                MarkdownViewerWindow.Init(); // 打开窗口
            }
        }
    }

}
